package com.tianji.promotion.utils;

import com.tianji.common.exceptions.BizIllegalException;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;

@Aspect
@RequiredArgsConstructor
public class MyLockAspect implements Ordered {

    private final RedissonClient redissonClient;

    @Around("@annotation(myLock)")
    public Object tryLock(ProceedingJoinPoint pjj, MyLock myLock) throws Throwable {
        RLock lock = redissonClient.getLock(myLock.name());
        boolean isLock = lock.tryLock(myLock.waiTime(), myLock.leaseTime(), myLock.unit());
        if (!isLock) {
            throw new BizIllegalException("请求太频繁");
        }
        try {
            return pjj.proceed();
        } finally {
            lock.unlock();
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
